﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Linq;
using Atmk.WaterMeter.MIS.Entities;
using Atmk.WaterMeter.MIS.GateWay.CT_NBIoT.ViewModel.CallBack;
using Atmk.WaterMeter.MIS.TestForm.Common;
using Atmk.WaterMeter.MIS.TestForm.Views.DataMock.vo;
using Common.Logging;
using NKnife.IoC;
using RestSharp;

namespace Atmk.WaterMeter.MIS.TestForm.Views.DataMock.Helper
{
    internal class UtilHistory
    {
        private static readonly ILog _Logger = LogManager.GetLogger<UtilHistory>();
        private static readonly string _GatewayId = Guid.NewGuid().ToString("N");
        private readonly CurrentMock _current;
        private readonly KeyDataBuilder _dataBuilder = new KeyDataBuilder();

        private readonly Kernel _kernel;

        public UtilHistory()
        {
            _kernel = DI.Get<Kernel>();
            _current = DI.Get<CurrentMock>();
        }

        public void Run()
        {
            foreach (var meter in _current.MeterMap)
            {
                BuildSingleMeterHistoryData(meter);
            }
        }

        private void BuildSingleMeterHistoryData(KeyValuePair<string, MeterAndOwner> meter)
        {
            var now = DateTime.Now;

            var data = BuildDeviceData(meter.Key);
            var date = DateTime.ParseExact(data.service.eventTime, "yyyyMMddTHHmmssZ", CultureInfo.CurrentCulture);

            while (!(now.Year == date.Year && now.Month == date.Month && now.Day == date.Day))
            {
                var request = new RestRequest(UrlManager.DeviceDataChanged, Method.POST);
                request.AddHeader("X-Token", _kernel.Token);
                request.AddJsonBody(data);
                _Logger.Debug(data);
                _kernel.Client.ExecuteAsync(request, response =>
                {
                    var resp = response.Content;
                    _Logger.Trace(resp);
                });
                data = BuildDeviceData(meter.Key);
                date = DateTime.ParseExact(data.service.eventTime, "yyyyMMddTHHmmssZ", CultureInfo.CurrentCulture);
                Thread.Sleep(5);
            }
        }

        private DeviceDataPost BuildDeviceData(string meter)
        {
            var data = new DeviceDataPost {deviceId = meter};
            FillSimpleValue(data);
            var keyData = _dataBuilder.GetKeyData(meter);
            var current = Convert.ToBase64String(BitConverter.GetBytes(keyData.Current * 100
            ).Reverse().Take(2).ToArray());
            data.service = new DeviceServiceData
            {
                data = new DeviceData
                {
                    current = current,
                    history = BuildHistory(keyData.History),
                    valve = keyData.Valve,
                    voltage = (int) (keyData.Voltage * 100 - 100),
                    warning = 0
                },
                eventTime = keyData.Time.ToString("yyyyMMddTHHmmssZ"),
                serviceId = "SID",
                serviceType = "STY"
            };
            return data;
        }

        public string BuildHistory(float[] array)
        {
            var data = new List<byte>();
            foreach (var t in array)
            {
                var bytes = BitConverter.GetBytes((int) (t * 100));
                data.AddRange(bytes);
            }

            return Convert.ToBase64String(data.ToArray());
        }

        //DateTime.ParseExact(value, "yyyyMMddTHHmmssZ", CultureInfo.CurrentCulture);

        private void FillSimpleValue(DeviceDataPost data)
        {
            data.gatewayId = _GatewayId;
            data.notifyType = "hello_Notify";
            data.requestId = Guid.NewGuid().ToString("N");
        }
    }
}